package com.sj.uabrowser.mvp.main.view.act;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.just.agentweb.AgentWeb;
import com.orhanobut.logger.Logger;
import com.sj.uabrowser.R;
import com.sj.uabrowser.app.StatusBarUtil;
import com.sj.uabrowser.db.CollectHistory;
import com.sj.uabrowser.db.gen.CollectHistoryDao;
import com.sj.uabrowser.framework.BaseActivity;
import com.sj.uabrowser.framework.BasePresenter;
import com.sj.uabrowser.net.AuthResultClient;
import com.sj.uabrowser.net.ServiceApi;

import java.util.Date;
import java.util.List;

import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class KeyWdAct extends BaseActivity {

    FrameLayout mViewParent;
    private AgentWeb mAgentWeb;
    private CollectHistory bean;
    private CollectHistoryDao collectHistoryDao;
    private String url;

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_key_wd;
    }

    @OnClick(R.id.iv_pre)
    public void onClick(){
        onBackPressed();
    }


    @Override
    public void setView() {
        url = getIntent().getStringExtra("searchUrl");
        Logger.e("searchUrl:"+url);
        StatusBarUtil.setTransparentForImageView(this,null);
        mViewParent = findViewById(R.id.viewParent);
        loadSearchPage(url);
    }

    @Override
    public void setData() {

    }

    private void loadSearchPage(String url) {
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mViewParent, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(webViewClient)
                .createAgentWeb()
                .ready()
                .go(url);
        WebView webView = mAgentWeb.getWebCreator().getWebView();
//        WebView初始化之后需要添加如下代码开启Cookie：
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        } else {
            CookieManager.getInstance().setAcceptCookie(true);
        }
        WebSettings webSettings = webView.getSettings();
        webSettings.setSupportZoom(true);
        //支持javascript
        webSettings.setJavaScriptEnabled(true);
// 设置可以支持缩放
        webSettings.setSupportZoom(true);
// 设置出现缩放工具
        webSettings.setBuiltInZoomControls(true);
//扩大比例的缩放
        webSettings.setUseWideViewPort(true);
//自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        webSettings.setLoadWithOverviewMode(true);
//        webView.setDownloadListener(new DownloadListener() {
//            @Override
//            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//                Intent intentUrl = new Intent(BrowserActivity.this, SearchAct.class);
//                intentUrl.putExtra("httpurl", url);
//                startActivity(intentUrl);
//                finish();
//            }
//        });
    }

    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Uri uri = request.getUrl();
            String uriOverride = uri.toString();
            Log.e("uriOverride:", uriOverride);
            if (uriOverride.startsWith("baiduboxlite://")
                    || uriOverride.startsWith("baiduboxapp://")
                    || uriOverride.startsWith("iqiyi://")
                    || uriOverride.startsWith("https://mo.baidu.com/boxandroid")
                    || uriOverride.startsWith("tbopen://")

            ) {
                return true;
            }
            return false;
        }


        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Uri uri = request.getUrl();


            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mAgentWeb != null) {
                mAgentWeb.getIndicatorController().setProgress(100);
            }
            if(!noTrace) {
                collectHistoryDao = daoSession.getCollectHistoryDao();
                List<CollectHistory> histories = collectHistoryDao.queryRaw("where url = ?", new String[]{url});
                if (histories.size() == 0) {
                    bean = new CollectHistory();
                    bean.setUrl(KeyWdAct.this.url);
                    bean.setDate(new Date().getTime());
                    bean.setType(CollectHistory.TYPE_KEYWORDS);
                    String keywords = getIntent().getStringExtra("keywords");
                    bean.setTitle("网页搜索_" + keywords);
                    bean.setIsHis(true);
                    collectHistoryDao.insert(bean);
                } else {
                    bean = histories.get(0);
                    bean.setDate(new Date().getTime());
                    collectHistoryDao.update(bean);
                }
            }
        }
    };

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (mAgentWeb.getWebCreator().getWebView().canGoBack()) {
            mAgentWeb.getWebCreator().getWebView().goBack();
        } else
            super.onBackPressed();
    }



}
